package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService{
    @Autowired
    private PermissionMapper mapper;
    //请求映射处理映射器
    @Autowired
    private RequestMappingHandlerMapping rmhm;

    public void save(Permission entity) {
        mapper.insert(entity);
    }

    public List<Permission> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Permission> rows = mapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    //加载系统权限
    public void reload() {
        //0:排重
        List<Permission> permissions = mapper.selectAll();
        Set<String> set = new HashSet<>();
        for (Permission s : permissions) {
            set.add(s.getResource());
        }

        //1:通过请求的映射处理映射器
        //2:通过请求的映射处理映射器对象获取该对象所有的方法
        Map<RequestMappingInfo, HandlerMethod>  handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        if(values == null) {
            return;
        }
        for (HandlerMethod hm : values) {
            //3:遍历方法对象, 判断方法上面是否拥有RequiresPermissions注解
            RequiresPermissions ann = hm.getMethodAnnotation(RequiresPermissions.class);
            if(ann != null){
                //shiro权限注解value是数组,返回就是数组
                String resource = ann.value()[0];
                if(set.contains(resource)){
                    continue;
                }
                String name  = hm.getMethodAnnotation(PermissionName.class).value();
                //如果已经存在跳过

                //获取权限名称
                //4:如果解析注解,获取权限表达式, 然后封装成Permission对象然后保存
                Permission permission = new Permission();
                permission.setName(name);
                permission.setResource(resource);
                mapper.insert(permission);
            }
        }
    }

    public List<Permission> queryPermissionByRoleId(Long roleId) {
        return mapper.queryPermissionByRoleId(roleId);
    }

    public List<String> getPermissionResourceByEmpId(Long id) {
        return mapper.getPermissionResourceByEmpId(id);
    }

}
